/**create by liuhua at 2019年6月13日 上午11:33:57**/
package com.star.truffle.core.mybatis.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.star.truffle.core.jackson.StarJson;

public class ArrayForStringHandler extends BaseTypeHandler<String[]> {

  private StarJson starJson = new StarJson(new ObjectMapper());

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
    String val = null;
    if(null != parameter) {
      val = starJson.obj2string(parameter);
    }
    ps.setString(i, val);
  }

  @Override
  public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
    return parse(rs.getString(columnName));
  }

  @Override
  public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    return parse(rs.getString(columnIndex));
  }

  @Override
  public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    return parse(cs.getString(columnIndex));
  }

  private String[] parse(String val) {
    if(StringUtils.isBlank(val)) {
      return new String[] {};
    }
    return starJson.str2obj(val, String[].class);
  }
}
